package com.example.ecommercedemo.controller;

import com.example.ecommercedemo.utils.Base64;
import com.example.ecommercedemo.utils.PassToken;
import com.example.ecommercedemo.utils.ServerResponse;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CodeController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Value("char")
    private String captchaType;

    @Autowired
    private RedisTemplate redisTemplate;

    @PassToken
    @GetMapping("/getCheckCode")
    public ServerResponse getCheckCode(HttpServletResponse response){
        //保存验证码信息
        String uuid= UUID.randomUUID()+"";
        String verifyKey="captcha_codes:"+uuid;
        String capStr=null,code=null;
        BufferedImage image=null;

        capStr=code=captchaProducer.createText();//45EE
        System.out.println(code);
        image=captchaProducer.createImage(capStr);//创建验证码图片

        redisTemplate.opsForValue().set(verifyKey,code,2, TimeUnit.MINUTES);
        //转换信息写出
        FastByteArrayOutputStream os=new FastByteArrayOutputStream();
        try {
                ImageIO.write(image,"jpg",os);
        }catch(IOException e){
                return ServerResponse.createByFail(500,"获取验证码失败");
            }
        Map<String,Object> map=new HashMap<>();
        map.put("uuid",uuid);
        map.put("img", Base64.encode(os.toByteArray())); //输出流转换成base64编码
        return ServerResponse.createBySuccess(200,map,"获取成功");

    }
}
